import { delAlgor, getAlgor } from "@/apis/algor"
import {
  Card, Breadcrumb, Table, Space, Button, Tag, Popconfirm, message
} from "antd"
import {
  CaretDownOutlined,
  CaretUpOutlined,
  EditOutlined,
  LinkOutlined,
  UploadOutlined,
  DeleteOutlined,
  ExportOutlined
} from '@ant-design/icons'
import { useEffect, useState } from "react"
import { Link } from "react-router-dom"
import DrawerForm from "./components/Drawer"
import CollectionCreateFormModal from "./components/CollectionCreateFormModal"
import './index.scss'
import { ExportExcel, paginationConfig } from "@/utils"


const Algor = () => {
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
      ellipsis: true,
      width: 100,
      style: {
        maxWidth: 100
      }
    },
    {
      title: '算法名',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '算法描述',
      dataIndex: 'title',
      key: 'title',
      align: 'center',
      ellipsis: true,
    },
    {
      title: '算法链接',
      dataIndex: 'url',
      key: 'url',
      align: 'center',
      ellipsis: true,
      width: 120,
      style: {
        maxWidth: 120
      },
      render: (text) => (
        <Button
          href={`http://${text}`}
          target="_blank"
          rel="noopener noreferrer"
          icon={<LinkOutlined />}
          type="primary"
          style={{
            background: '#a0d911'
          }}
        >
          链接
        </Button>)
    },
    {
      title: '算法标签',
      dataIndex: 'tag',
      key: 'tag',
      align: 'center',
      ellipsis: true,
      render: (text) => renderTag(text)
    },
    {
      title: '修改日期',
      dataIndex: 'date',
      key: 'date',
      align: 'center',
      ellipsis: true
    },
    {
      title: '操作',
      dataIndex: '',
      key: 'x',
      align: 'center',
      ellipsis: true,
      render: (record) => {
        const isExpanded = expandedRowKeys.includes(record.key)
        return (
          <Space>
            <Button
              icon={<EditOutlined />}
              type="primary"
              style={{ background: "#fa8c16", }}
              onClick={() => showDrawer(record)}
            >
              编辑
            </Button>
            <Button onClick={() => show(record)} type="primary"
              icon={isExpanded ? <CaretUpOutlined /> : <CaretDownOutlined />} >
              {isExpanded ? '收起' : '查看'}
            </Button>
            <Popconfirm
              title="删除这条算法"
              description="你确定要删除这条算法吗?"
              onConfirm={() => confirm(record)}
              // onCancel={cancel}
              okText="是"
              cancelText="否"
            >
              <Button
                icon={<DeleteOutlined />}
                type="primary"
                style={{
                  backgroundColor: '#f5222d'
                }}
              >
                删除
              </Button>
            </Popconfirm>
          </Space>
        )
      }
    }
  ]

  const [data, setData] = useState([])
  const [expandedRowKeys, setExpandedRowKeys] = useState([])

  // 删除算法气泡弹框确认
  const confirm = async (record) => {
    // console.log(record.table_id)
    await delAlgor(record.table_id)
    getAlgorList()
    // message.success('删除算法成功')
  }

  const [buttonText, setButtonText] = useState('查看')

  const show = (record) => {
    const { id: key } = record
    const filtered = expandedRowKeys
    if (expandedRowKeys.includes(key)) {
      filtered.splice(filtered.findIndex(element => element === key), 1)
    } else {
      filtered.push(key)
    }
    setExpandedRowKeys(filtered)
    const Text = filtered.includes(key) ? '收起' : '查看'
    setButtonText(Text)
  }

  const renderTag = (text) => {
    const colors = ['magenta', 'red', 'orange', 'green', "cyan", "purple"]
    const tagData = text.split('-')
    const res = tagData.map((tag, index) => {
      return (
        <Tag key={tag} color={colors[index]}>{tag}</Tag>
      )
    })
    return res

  }


  const processedData = (data) => {
    if (data) {
      return data.map((row, rowIndex) => {
        let rowData = {
          key: rowIndex + 1,
          id: rowIndex + 1,
          name: row[1],
          title: row[2],
          date: row[3],
          url: row[4],
          tag: row[6],
          description: row[7],
          table_id: row[0]
        }
        return rowData
      })
    }
  }


  const getAlgorList = async () => {
    const res = await getAlgor()
    setData(processedData(res))
  }

  useEffect(() => {
    const getAlgorList = async () => {
      const res = await getAlgor()
      setData(processedData(res))
    }
    getAlgorList()

  }, [])


  const [open, setOpen] = useState(false)
  const showDrawer = (record) => {
    setEditData(record)
    setOpen(true)
  }
  const onClose = () => {
    setOpen(false)
  }

  const [editData, setEditData] = useState({}) // 需要回填的数据

  // 添加算法
  const [add, setAdd] = useState(false)
  const onCreate = async (values) => {
    // console.log('Received values of form: ', values)
    // setOpen(false)
    const res = await getAlgor()
    setData(processedData(res))
  }

  // 导出
  const exportExcel = () => {
    ExportExcel(columns, data, 'Algorithms')
  }

  return (
    <div className="table">
      <Card
        title={
          <Breadcrumb items={[
            { title: <Link to={'/'}>首页</Link> },
            { title: '算法列表' },
          ]}
            className='breadcrumb'
          />
        }
      >
        <Space style={{ marginBottom: 20, marginTop: 10 }}>
          <Button
            type="primary"
            icon={<UploadOutlined />}
            onClick={() => setAdd(true)}
            style={{
              background: '#722ed1'
            }}
          >
            上传算法
          </Button>
          <Button type='primary' onClick={exportExcel} icon={<ExportOutlined />}>导出表格</Button>
        </Space>
        <Table
          bordered
          pagination={paginationConfig}
          columns={columns}
          dataSource={data}
          expandable={{
            expandedRowRender: record => <p style={{ margin: 0, maxWidth: '100', whiteSpace: 'pre-wrap' }}>{record.description}</p>,
            expandedRowKeys: expandedRowKeys,
            expandRowByClick: true
          }}
          expandIconAsCell={false}
          expandIconColumnIndex={-1}
          scroll={{
            y: 'calc(100vh - 450px)',
            x: 'auto'
          }}
        >
          {/* expandIconAsCell={false} */}

        </Table>
      </Card>

      <DrawerForm
        visible={open}
        onClose={onClose}
        initialValues={editData}
        getAlgorList={getAlgorList}
      />

      <CollectionCreateFormModal
        open={add}
        onCreate={onCreate}
        onCancel={() => setAdd(false)}
        getAlgorList={getAlgorList}
      />

    </div >
  )
}




export default Algor